package com.arraymasterx.algorithm.search;

import com.arraymasterx.config.AlgorithmConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class BinarySearch implements SearchAlgorithm {

    private final AlgorithmConfig algorithmConfig;

    @Autowired
    public BinarySearch(AlgorithmConfig algorithmConfig) {
        this.algorithmConfig = algorithmConfig;
    }

    @Override
    public int search(int[] array, int target) {
        validateInput(array);

        int left = 0;
        int right = array.length - 1;

        while (left <= right) {
            int mid = left + (right - left) / 2;

            if (array[mid] == target) {
                return mid;
            } else if (array[mid] < target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }

        return -1;
    }

    private void validateInput(int[] array) {
        if (array == null) {
            throw new IllegalArgumentException("Input array cannot be null");
        }

        if (array.length == 0) {
            throw new IllegalArgumentException("Input array is empty");
        }

        if (array.length > algorithmConfig.getSearch().getMaxArraySize()) {
            throw new IllegalArgumentException(
                    "Array size exceeds maximum allowed size: " + algorithmConfig.getSearch().getMaxArraySize());
        }

        // 验证数组是否已排序
        for (int i = 0; i < array.length - 1; i++) {
            if (array[i] > array[i + 1]) {
                throw new IllegalArgumentException("Input array must be sorted in ascending order");
            }
        }
    }
}